import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Table, Tag, Tooltip, Modal, message } from "antd";
import React, { useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef, } from "react";
import { WarningOutlined, LeftOutlined, CloseOutlined, } from "@ant-design/icons";
import DevGrid from "~/public/cpas-ui/components-ui/express-components/DevGrid";
import CpasTable from "../../HandSonGrid";
// import resultJson from "./default.json";
// import { getBaseDataApi } from "../../api/DesignTableApi";
import ScrollView from "devextreme-react/scroll-view";
import { Popup, Position } from "devextreme-react/popup";
// import { columns as testColumns } from "./data";
import { getYears, formatPrice, transformCrossData, } from "../../../../tools/Tools";
import { getDisclosureData, getCpasTableByName, getCpasTableList, } from "../../api/DesignTableApi";
import { sortValidtorData } from "./../../../CpasNotes/utils";
import { devCellScrollPositionBySelected, devCellSelected, } from "../../classes/DevTableService";
import { DataGridOptions } from "../MenuTool/cellData/CommonOption";
const noneFormatText = "【无效公式】";
let dataCol = localStorage.getItem("tableColums")
    ? JSON.parse(localStorage.getItem("tableColums"))
    : [];
dataCol.forEach((item) => {
    if (item.alignment === "right") {
        item["dataTypeCustom"] = "money-number";
    }
    console.log(item);
});
const findAntTabsTabPane = (element) => {
    if (!element) {
        return null;
    }
    let parent = element.parentNode;
    while (parent) {
        if (parent.classList?.contains("tab-root")) {
            return parent;
        }
        parent = parent.parentNode;
    }
    return null; // 如果未找到符合条件的父元素，返回 null
};
/**
 *
 * @param
 * isOpen: boolean, // 是否打开弹框   必传
 * handleOpen: any, // 关闭弹框事件  必传
 * result:[], // 校验详情显示结果  必传
 * resultList:[], // 非必传 校验详情 设置公式
 * isBackAll: boolean,  // 过滤显示 校验详情 是否 返回全部  true 显示 返回全部  false 不显示
 * onBackAll: any,  // 点击返回全部 事件
 * params: any,  // caps-table ref
 * noTransform: boolean 整理模式需要在DS组件中转换为单条或取，故不需要在详情中再次转换数据
 * @returns
 */
const DetailModal = forwardRef((props, ref) => {
    const { isOpen, handleOpen, result, resultList, isBackAll = false, onBackAll, params, } = props;
    console.warn("校验详情", props);
    const [isOpenModal, setIsOpenModal] = useState(false);
    const isFirstTimeOpen = useRef(true);
    const [isOpenPopup, setIsOpenPopup] = useState(false);
    const [typeTable, setTypeTable] = useState({});
    const [resultJson, setResultJson] = useState(null);
    const [allResult, setAllResult] = useState([]);
    const rules = {
        "1": "表内校验",
        "2": "表间校验",
        "3": "与报表校验",
        "4": "交叉校验",
    };
    // const cpasTableRef = useRef(null);
    const devGridRef = useRef(null);
    const defultRef = useRef();
    const gridRefs = useRef(null);
    const [columnsDatas, setColumnsData] = useState([]);
    const [dataRef, setDataRef] = useState({});
    const [baseList, setBaseList] = useState([]);
    const [yearNum, setYearNum] = useState();
    const [state, setState] = useState(-1);
    const [cpasResultData, setCpasResultData] = useState(null);
    const [isClickInvalidBtn, setClickInvalidBtn] = useState(false);
    const devCoordsRef = useRef({ rmap: "", cmap: "" });
    const currentRootRef = useRef(null);
    const currentContentRef = useRef(null);
    const popupRef = useRef(null);
    useEffect(() => {
        if (currentContentRef.current) {
            currentRootRef.current = findAntTabsTabPane(currentContentRef.current);
        }
    }, []);
    useEffect(() => {
        const tabEl = findAntTabsTabPane(currentContentRef.current);
        // 创建一个 MutationObserver 实例
        const observer = new MutationObserver((mutationsList, observer) => {
            for (let mutation of mutationsList) {
                if (mutation.type === "attributes" &&
                    mutation.attributeName === "tabindex") {
                    const currentTabIndex = tabEl.getAttribute("tabindex");
                    if (currentTabIndex === "0") {
                        if (popupRef.current) {
                            popupRef.current.instance.repaint();
                        }
                        console.log("Tabindex of the target element is now 0");
                    }
                }
            }
        });
        // 配置观察选项
        const config = {
            attributes: true,
            attributeOldValue: true,
            attributeFilter: ["tabindex"],
        };
        if (tabEl) {
            // 开始观察目标元素的属性变化
            observer.observe(tabEl, config);
        }
        // 在组件卸载时停止观察器
        return () => {
            observer.disconnect();
        };
    }, []); // 仅在组件挂载和卸载时运行
    const columns = [
        {
            title: "年度",
            dataIndex: "year",
            key: "year",
            width: 100,
            // fixed: "left",
            ellipsis: true,
        },
        {
            title: "表名",
            dataIndex: "formatTName",
            key: "formatTName",
            width: 200,
            ellipsis: true,
            render: (_, record) => {
                return (_jsx("div", { children: _jsx("span", { children: _ === "base.reportItems" ? "报表基础数据" : _ }) }));
            },
        },
        {
            title: "行项目",
            dataIndex: "projectName",
            key: "projectName",
            width: 150,
            ellipsis: true,
        },
        {
            title: "列项目",
            dataIndex: "pathLabel",
            key: "pathLabel",
            width: 200,
            ellipsis: true,
        },
        {
            title: "金额",
            dataIndex: "value",
            key: "value",
            width: 100,
            ellipsis: true,
            render(text, record, index) {
                let val = text;
                if (val) {
                    if (typeof text === "string") {
                        val = Number(text);
                    }
                    if (parseInt(val) === 0) {
                        return "";
                    }
                    else {
                        return formatPrice(val.toFixed(2));
                    }
                }
                else {
                    return "";
                }
            },
        },
    ];
    useEffect(() => {
        // setDataRef(devGridRef.current);
        initReload({ dateId: "本年" });
    }, []);
    useImperativeHandle(ref, () => ({
        closeCheckDetail: () => {
            setIsOpenPopup(false);
        },
    }));
    useEffect(() => {
        setIsOpenPopup(isOpen);
    }, [isOpen]);
    useEffect(() => {
        const curr = defultRef?.current;
        if (curr && curr?.hot) {
            setTimeout(() => {
                curr?.hot.render();
            }, 1000);
        }
    }, [cpasResultData]);
    const initReload = async (e) => {
        const dateIds = await getYears(e.dateId || "本年");
        setYearNum(dateIds);
        const data = await getDisclosureData({
            name: "base.reportItems",
            data_id: dateIds,
            fields: [],
            where: "",
            order: "",
        });
        if (data.ok) {
            let row = 0;
            let col = 0;
            data.data.map((item, index) => {
                if (item["主键"] === e.rMap) {
                    row = index * 40;
                    Object.keys(item).map((m, idx) => {
                        if (m === e.cMap) {
                            col = (idx - 1) * 120;
                        }
                    });
                }
            });
            // const scrollData =
            //   devGridRef.current?.gridRef.current?.instance.getScrollable();
            // if (scrollData) {
            //   scrollData.scrollTo({ left: col, top: row });
            // }
            return setBaseList([...data.data]);
        }
        else {
            return message.error(" 数据获取失败");
        }
    };
    const onRowDoubleClick = async (e, item) => {
        setTypeTable({ ...e, ...item });
        setIsOpenModal(true);
        if (item.type === "3") {
            const { projectName, pathLabel } = e;
            devCoordsRef.current = { rmap: projectName, cmap: pathLabel };
            initReload(e);
        }
        else if (item.type !== "1") {
            const current = defultRef.current;
            current?.reRender();
            console.error(e, item);
            if (e.type === "IN_CELL") {
                return;
            }
            const formulaCpasType = e.formulaCpasType;
            if (formulaCpasType === "ds" || formulaCpasType === "zl") {
                const dateIds = await getYears(e.data_id);
                setYearNum(dateIds);
                const list = await getCpasTableByName(e.tableName.split("|")[0], dateIds, formulaCpasType);
                if (list.ok) {
                    const params = {
                        tid: list.data.tid,
                        type: list.data.type,
                        data_type: "json",
                        grid_data_type: "display",
                    };
                    const tableData = await getCpasTableList(params);
                    const curr = defultRef.current;
                    setCpasResultData(tableData.data);
                    await curr?.reloadTable(tableData.data, null, null, true);
                    const colum = curr?.getCellCoordsByRmapCmap(e.rMap, e.cMap);
                    curr?.hot.selectCell(colum.row, colum.col);
                    curr?.reRender();
                }
            }
            else {
                setYearNum(null);
                const list = await getCpasTableByName(e.tableName, "", "fs");
                if (list.ok) {
                    const params = {
                        tid: list.data.tid,
                        type: list.data.type,
                        data_type: "json",
                        grid_data_type: "display",
                    };
                    const tableData = await getCpasTableList(params);
                    const curr = defultRef.current;
                    setCpasResultData(tableData.data);
                    await curr?.reloadTable(tableData.data, null, null, true);
                    const colum = curr?.getCellCoordsByRmapCmap(e.rMap, e.cMap);
                    curr?.hot.selectCell(colum.row, colum.col);
                    curr?.reRender();
                }
            }
        }
    };
    const markTableData = (item, index) => {
        if (isClickInvalidBtn && params?.current) {
            return params?.current?.articulationVerifyService?.clearArtVerifyMark();
        }
        // //bydingxiaofei20241119 跟兴哥商量后，交叉校验需要按表内校验标记。
        // if (item.type === "4") {
        //   item.type = "1";
        // }
        if (index === state) {
            setState(-1);
            if (params.current?.articulationVerifyService) {
                params.current.articulationVerifyService.artResultItem = [];
                const formularList = transformCrossData(params?.current?.articulationVerifyService?.artParseResultList);
                params.current.articulationVerifyService.clearArtVerifyMark();
                params.current.articulationVerifyService.batchMarkBeVerifiedItem(formularList);
            }
            else if (params.current.zlTableRef) {
                const newList = getAllCheckData?.validList;
                params.current.zlTableRef.current.articulationVerifyService.clearArtVerifyMark();
                params.current.zlTableRef.current.articulationVerifyService.batchMarkBeVerifiedItem(newList);
            }
            else if (params.current?.handsonTableFs.current.articulationVerifyService) {
                const newList = getAllCheckData?.validList;
                params.current.handsonTableFs.current.articulationVerifyService.clearArtVerifyMark();
                params.current.handsonTableFs.current.articulationVerifyService.batchMarkBeVerifiedItem(newList);
            }
        }
        else {
            setState(index);
            if (params.current?.articulationVerifyService) {
                params.current.articulationVerifyService.artResultItem = [item];
                params.current.articulationVerifyService.clearArtVerifyMark();
                params.current.articulationVerifyService.markBeVerifiedItem(item, true, true);
            }
            else if (params.current.zlTableRef) {
                params.current.zlTableRef.current.articulationVerifyService.clearArtVerifyMark();
                params.current.zlTableRef.current.articulationVerifyService.markBeVerifiedItem(item, true, true);
            }
            else if (params.current?.handsonTableFs.current.articulationVerifyService) {
                params.current.handsonTableFs.current.articulationVerifyService.clearArtVerifyMark();
                params.current.handsonTableFs.current.articulationVerifyService.markBeVerifiedItem(item, true, true);
            }
        }
    };
    const titleRender = () => {
        const invalidList = getAllCheckData?.invalidList;
        let renderBack = null;
        if (isBackAll) {
            renderBack = (_jsxs("span", { onClick: () => buttonClick(), style: { color: "#4f2d7f" }, className: "closebtns", children: [_jsx(LeftOutlined, {}), "\u8FD4\u56DE\u5168\u90E8"] }));
        }
        if (invalidList && invalidList.length) {
            if (!isClickInvalidBtn) {
                renderBack = (_jsxs("span", { onClick: () => setClickInvalidBtn(true), style: { color: "#4f2d7f" }, className: "closebtns", children: [invalidList.length, "\u6761\u65E0\u6548\u516C\u5F0F"] }));
            }
            else {
                renderBack = (_jsxs("span", { onClick: () => {
                        setClickInvalidBtn(!isClickInvalidBtn);
                    }, style: { color: "#4f2d7f" }, className: "closebtns", children: [_jsx(LeftOutlined, {}), "\u8FD4\u56DE"] }));
            }
        }
        return (_jsxs("div", { className: "title-render", children: [_jsx("div", { children: _jsxs("span", { style: { marginLeft: "10px" }, children: [_jsx(WarningOutlined, { style: { color: "red", marginRight: "3px" } }), "\u6821\u9A8C\u8BE6\u60C5"] }) }), _jsxs("div", { className: "title-ri", children: [_jsx("div", { style: { paddingRight: 10 }, children: renderBack }), _jsx("div", { className: "closebtns", children: _jsx("span", { onClick: () => {
                                    handleOpen();
                                    onBackAll();
                                    setAllResult([]);
                                    setClickInvalidBtn(false);
                                }, children: _jsx(CloseOutlined, {}) }) })] })] }));
    };
    const buttonClick = () => {
        const formulaList = transformCrossData(params.current.articulationVerifyService.artParseResultList);
        setAllResult(formulaList);
        params.current.articulationVerifyService.batchMarkBeVerifiedItem(formulaList);
    };
    const getAllCheckData = useMemo(() => {
        const noneFormatText = "【无效公式】";
        let tempList = null;
        let newList = [];
        if (allResult.length === 0) {
            tempList = result;
        }
        else {
            tempList = allResult;
        }
        if (tempList) {
            newList = transformCrossData(tempList, isBackAll);
        }
        let validList = [];
        let invalidList = [];
        for (let i = 0; i < newList.length; i++) {
            const { fullFormulaResult, beVerifyFormat, verifyFormat, dynamicType, verifyIsNA, beVerifyIsNA, } = newList[i];
            if ((dynamicType !== "MAIN" && beVerifyIsNA) ||
                (dynamicType !== "MAIN" && verifyIsNA)) {
                invalidList.push({
                    ...newList[i],
                });
            }
            else if (!fullFormulaResult) {
                validList.push({
                    ...newList[i],
                });
            }
        }
        validList = sortValidtorData(validList);
        invalidList = sortValidtorData(invalidList);
        console.log(invalidList, "invalidList--");
        return {
            validList,
            invalidList,
        };
    }, [allResult, result]);
    const formatNum = (item) => {
        const { verifyFormulaResult, beVerifiedFormulaResult } = item;
        if (!verifyFormulaResult && !beVerifiedFormulaResult) {
            return 0;
        }
        const tempVerifyFormulaResult = verifyFormulaResult
            ? Number(verifyFormulaResult).toFixed(2)
            : 0;
        const tempBeVerifiedFormulaResult = beVerifiedFormulaResult
            ? Number(beVerifiedFormulaResult).toFixed(2)
            : 0;
        const fixedNum = Number(tempVerifyFormulaResult) - Number(tempBeVerifiedFormulaResult);
        const sourceNum = Number(verifyFormulaResult) - Number(beVerifiedFormulaResult);
        if (fixedNum === 0 && sourceNum < 0.01) {
            return Number(sourceNum ? sourceNum.toFixed(6) : 0);
        }
        return formatPrice(fixedNum ? fixedNum.toFixed(2) : 0);
    };
    const displayNum = (item, type) => {
        const { verifyFormulaResult, beVerifiedFormulaResult } = item;
        const tempVerifyFormulaResult = verifyFormulaResult
            ? Number(verifyFormulaResult).toFixed(2)
            : 0;
        const tempBeVerifiedFormulaResult = beVerifiedFormulaResult
            ? Number(beVerifiedFormulaResult).toFixed(2)
            : 0;
        const fixedNum = Number(tempVerifyFormulaResult) - Number(tempBeVerifiedFormulaResult);
        const sourceNum = Number(verifyFormulaResult) - Number(beVerifiedFormulaResult);
        const value = type === "verify" ? verifyFormulaResult : beVerifiedFormulaResult;
        if (fixedNum === 0 && sourceNum < 0.01) {
            return Number(value);
        }
        const tempValue = value ? Number(value).toFixed(2) : 0;
        return formatPrice(tempValue);
    };
    const { validList, invalidList } = getAllCheckData;
    const renderList = (data, isShowTable) => {
        if (!data || !data.length) {
            return _jsx("div", { className: "rules", children: "\u6682\u672A\u8BBE\u7F6E\u6821\u9A8C\u89C4\u5219" });
        }
        // const newList = isClickInvalidBtn ? invalidList : validList;
        // console.log(newList, 'newList--------', isClickInvalidBtn);
        return data.map((item, index) => {
            const { verifyFormulaList, beVerifyIsNA = false, verifyIsNA = false, beVerifyFormat, verifyFormat, } = item;
            const beVerifyText = beVerifyFormat ? beVerifyFormat.slice(1) : null;
            const verifyText = verifyFormat ? verifyFormat.slice(1) : null;
            return (_jsx(React.Fragment, { children: _jsxs("div", { className: !isClickInvalidBtn && state === index
                        ? "content-item content"
                        : "content", onClick: (e) => {
                        e.stopPropagation();
                        markTableData(item, index);
                    }, children: [_jsx("h5", { className: "content-title", children: _jsx("span", { children: `${item.number}: ${rules[item.type]}` }) }), _jsx("ul", { className: "details-list", children: _jsxs("li", { children: [_jsxs("div", { style: { marginBottom: 15 }, children: [_jsx(Tooltip, { title: item.fullFormula, trigger: "hover", zIndex: 99999, children: _jsx(Tag, { color: "#87d068", children: "\u516C\u5F0F" }) }), _jsx(Tag, { color: "#f50", children: item.isForce ? "强制" : "非强制" }), _jsx(Tag, { color: "#2db7f5", children: item.number }), _jsx(Tag, { color: !item.fullFormulaResult ? "#FD4037" : "#01B226", children: !item.fullFormulaResult ? "不通过" : "通过" })] }), _jsxs("div", { className: "valid-list", children: [_jsx("span", { children: "\u88AB\u6821\u9A8C\u9879(\u672C\u8868)\uFF1A" }), _jsxs("div", { children: [_jsx("div", { dangerouslySetInnerHTML: { __html: beVerifyText } }), _jsxs("span", { style: { color: "#00A7B5" }, children: ["=", beVerifyIsNA
                                                                ? `${displayNum(item, "beVerify")}(N/A)`
                                                                : displayNum(item, "beVerify")] })] })] }), _jsxs("div", { className: "valid-list", children: [_jsx("span", { children: "\u6821\u9A8C\u9879\uFF1A" }), _jsxs("div", { children: [_jsx("div", { dangerouslySetInnerHTML: { __html: verifyText } }), _jsxs("span", { style: { color: "#00A7B5" }, children: ["=", verifyIsNA
                                                                ? `${displayNum(item, "verify")}(N/A)`
                                                                : displayNum(item, "verify")] }), _jsxs("div", { style: { paddingTop: 8 }, children: [item.operation === "==" ? "差异:" : "结果:", _jsx("span", { style: {
                                                                    color: "rgb(253, 64, 55)",
                                                                    marginLeft: "5px",
                                                                }, children: item.operation === "=="
                                                                    ? formatNum(item)
                                                                    : item.operation !== "==" && !item.fullFormulaResult
                                                                        ? "逻辑不符"
                                                                        : "校验通过" })] })] })] }), isShowTable &&
                                        item.type !== "4" &&
                                        item.type !== "1" &&
                                        verifyFormulaList &&
                                        verifyFormulaList.length ? (_jsx("div", { className: "table-auto", children: _jsx(Table, { className: "tables", dataSource: verifyFormulaList, columns: columns, pagination: false, 
                                            // tableLayout={"auto"}
                                            bordered: true, rowKey: (record, index) => index, onRow: (record) => {
                                                if (record?.tableName !== "表内") {
                                                    return {
                                                        onDoubleClick: (e) => {
                                                            if (e?.type === "IN_CELL") {
                                                                return message.warning("当前表内项，不支持穿透～");
                                                            }
                                                            else {
                                                                e.stopPropagation();
                                                                onRowDoubleClick(record, item);
                                                            }
                                                        },
                                                    };
                                                }
                                                return;
                                            } }) })) : null] }) })] }, item.number) }));
        });
    };
    useEffect(() => {
        if (isOpenModal && typeTable.type === "3") {
            setTimeout(async () => {
                const { rmap, cmap } = devCoordsRef.current;
                await devCellScrollPositionBySelected(devGridRef, rmap, cmap, {
                    dataSource: baseList,
                    columns: dataCol,
                }, DataGridOptions.columnWidth, true);
                devCellSelected(devGridRef, rmap, cmap, null);
            }, 500);
            // resetScrollView(devGridRef);
        }
    }, [baseList, isOpenModal, typeTable.type]);
    // useEffect(() => {
    //   if (!isOpenModal) {
    //     isFirstTimeOpen.current = true; // 如果关闭弹出层，重置为首次打开状态
    //   } else {
    //     isFirstTimeOpen.current = false; // 如果打开弹出层，设置为非首次打开状态
    //   }
    // }, [isOpenModal]);
    return (_jsxs(React.Fragment, { children: [_jsx("div", { className: "dddd", ref: currentContentRef, children: _jsxs(Popup, { visible: isOpenPopup, width: "55vh", height: "80vh", ref: popupRef, dragEnabled: true, titleRender: titleRender, hideOnOutsideClick: false, container: currentRootRef.current, shading: false, wrapperAttr: { class: "check-detail" }, children: [_jsx(Position, { at: "right", my: "center", of: "", collision: "fit" }), _jsx(React.Fragment, { children: _jsx(ScrollView, { children: _jsx("div", { className: "details-modal-one", children: isClickInvalidBtn
                                        ? renderList(invalidList)
                                        : renderList(validList, true) }) }) })] }) }), _jsx(Modal, { open: isOpenModal, maskClosable: false, footer: null, onCancel: () => setIsOpenModal(false), className: "details-modal-two", forceRender: true, width: 900, destroyOnClose: true, zIndex: 998, children: _jsx("div", { children: typeTable.type === "2" ? (_jsxs(React.Fragment, { children: [yearNum ? (_jsxs("div", { className: "title-left ", children: [_jsx("label", { children: " \u5E74\u5EA6: " }), _jsx("span", { children: yearNum })] })) : null, _jsx("div", { className: "title-table", children: _jsx(CpasTable, { mapRowsList: [], mapColumnsList: [], tabGroup: "source-tab", tabLevel: 1, isTest: true, model: "read", isShowMenuToolBar: false, gridData: cpasResultData, ref: defultRef, type: "ds", name: "innerTable", numberZeroReplace: " " }) })] })) : (_jsxs(React.Fragment, { children: [_jsxs("div", { className: "title-left", children: [_jsx("label", { children: " \u5E74\u5EA6: " }), _jsx("span", { children: yearNum })] }), _jsx("div", { className: "title-table", style: { width: "100%", height: 500, overflow: "hidden" }, children: _jsx(DevGrid.RangeTap, { dataSource: baseList, defaultColumns: dataCol, scrolling: DataGridOptions.scrolling, paging: DataGridOptions.paging, 
                                    // columnMinWidth={DataGridOptions.columnWidth}
                                    onContentReady: (e) => {
                                        console.log("------------onContentReady-----------");
                                        if (isFirstTimeOpen.current) {
                                            // console.log("判断出首次打开 ,  执行滚动条重置");
                                            // resetScrollView(devGridRef);
                                        }
                                        if (isOpenModal && typeTable.type === "3") {
                                            const { rmap, cmap } = devCoordsRef.current;
                                            if (rmap && cmap) {
                                                devCellSelected(devGridRef, rmap, cmap, null);
                                            }
                                        }
                                    }, keyExpr: "\u4E3B\u952E", showBorders: true, ref: devGridRef, showColumnLines: true, showRowLines: true }) })] })) }) })] }));
});
export default DetailModal;
